<?php

require_once 'Mobitv/Admin/Action.php';

class SetpermAction extends Mobitv_Admin_Action
{
    public function execute()
    {
        $this->checkPermission();
        
        $userId = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $userDao = Vega_Dao::factory('Mobitv_Admin_Admin');
        $arrGroup = $userDao->getGroupList($userId);
        $this->_view->assign('arrGroup', $arrGroup);
        if(!$userId || !$user=$userDao->getDetail($userId)) {
            $this->forward404();
        }

        $actionDao = Vega_Dao::factory('Mobitv_Admin_Action');
        $modules = $actionDao->getModuleList();
        $permissions = $userDao->getPermissionList($userId);

        if($modules) {
            foreach($modules AS &$module) {
                $actions = array();
                foreach($permissions AS &$permission) {
                    if($permission['module']==$module['name']) {
                        $action['id'] = $permission['id'];
                        $action['name'] = $permission['name'];
                        $action['description'] = $permission['description'];
                        $action['perm'] = is_null($permission['permission']) ? 2 : $permission['permission'];

                        $actions[] = $action;
                    }
                }
                $module['actions'] = $actions;
            }
        }

        if($_POST) {
            $actionList = $actionDao->getList();
            foreach($actionList AS $action) {
                $field = "action-" . $action['id'];
                $perm = isset($_POST[$field]) ? $_POST[$field] : -1;
                if($perm==0 || $perm==1) {
                    $userDao->savePermission($userId, $action['id'], $perm);
                } else if($perm==2) {
                    $userDao->deletePermission($userId, $action['id']);
                }

            }

            $this->gotoUrl('/admin', 'Sửa thành công!');
        }

        $this->_view->assign('user', $user);
        $this->_view->assign('modules', $modules);
    }
}